package org.jeecg.modules.system.util;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.KM.entity.KmDoc;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author wt
 * @Date: 2024/7/2 15:00
 * @Description:
 */
@Slf4j
public class MaxKBUtil {

    /**
     * 登录并获取Token。
     *
     * @param username 用户名
     * @param password 密码
     * @return Token字符串，如果请求失败或响应不包含token，则返回null
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String loginAndGetToken(String username, String password, String ipAddress) throws IOException {
        String loginEndpoint= ipAddress +"/api/user/login";
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        log.info("========url==========="+url.openConnection());
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Postman-Token", "<calculated when request is sent>");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Length", "<calculated when request is sent>");
            connection.setRequestProperty("Host", "<calculated when request is sent>");
            connection.setRequestProperty("User-Agent", "PostmanRuntime/7.37.3");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("AUTHORIZATION", "eyJ1c2VybmFtZSI6ImFkbWluIiwiaWQiOiJmMGRkOGY3MS1lNGVlLTExZWUtOGM4NC1hOGExNTk1ODAxYWIiLCJlbWFpbCI6IiIsInR5cGUiOiJVU0VSIn0:1sJOCV:E97DN1fdd6_-Mb92br3Ro0LMJqnyDFYepgtH05zfOCI");
            connection.setRequestProperty("Accept", "application/json, text/plain, */*");
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,zh-TW;q=0.8,en-US;q=0.7,en;q=0.6");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Cookie", "Webstorm-5f995900=190abac4-9716-4b69-bf43-2dc82bd94ab1; sb-localhost-auth-token-code-verifier=%223f610884a20b6a33f8bd70367a1029db93cb97e9c2f6ada17a0574b19c0ef6ee59662ad3f57ded9533598849efe9101ea647f8b34c103bf1%2FPASSWORD_RECOVERY%22; __stripe_mid=5cc94e4f-33cf-4907-a470-4ed6a296cf2dedc790; _ga=GA1.1.1614442558.1715241741; _ga_FVWC4GKEYS=GS1.1.1715403475.2.0.1715403475.0.0.0; jenkins-timestamper-offset=-28800000; session=.eJzllV1vokAUhv8LSb1pV2b4HEzMxqpIFa1fVdcbwsIgtCODMCrY9L93dE23a1j_gMlJhswZ5rx5not5F5yMuQw7NPI9R1ma7fEePufxr8ehOc5bRqgZbfqqHxaB-yjU3gXfZe5xjWnsYaEmzMI2Djr2gKBZv7lsxdZ0uhAehBT7UYo95mzTiJ8KGUtqokio55KQZqymAgBEd8tCmkYHzH_YpuTvOQiqvAytqik1BAwgptgl60xcF6cPMUkpox4lIk1wHPk_PBrHfNjpwp8pzhIaZ9hhRYLrHvVxxSMRjpkT-fWAuNmb4yYJrHyPWD8OvpMbd5LJ6ysm3zkG5VtfUSuZx4fW_wy-x2s3Ivc8ThAR3jqCrF9nWDmBq5di-3gQcJ4INahDpEkQqEpVRggpCPHOd029fCu_5szcWPaIPc46O9vUlabU8PdJZxGWacK24b-xebE24cZqD6Ni0mjftqbrDM-aSrH9o4mXDqqyJgNZubAUFGZXW74EvjSddy0TIgQ6-CUem5I-syZlloi6lMe7mdrMgg2aZrlsacVtW7rO8GypFNulJQVUVYhkAC8shf15BKe73_1JZ7ts9A-qNkfj1Bj0dFntd8ssZfZuDCyjiZOktZXxKngCxm1bus7wbKkU26UlzgDoSFGhcaEpHuI5CNFgMNn5huQeJquoG1j5fLg6LHelLxPojZ6e2chctQ6uPV3ti4kS3Lam6wzPmkqxXWhCEqxCzZChxBsxztl_QYaYECp8fAJw6NRo.ZnAFbg.Sl3BiGaOylYh6J9vLOu5Ep788f4");
            connection.setRequestProperty("Origin", "http://localhost:3000");
            connection.setRequestProperty("Referer", "http://localhost:3000/ui/login");
            connection.setRequestProperty("Sec-Fetch-Dest", "empty");
            connection.setRequestProperty("Sec-Fetch-Mode", "cors");
            connection.setRequestProperty("Sec-Fetch-Site", "same-origin");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            connection.setRequestProperty("sec-ch-ua", "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"");
            connection.setRequestProperty("sec-ch-ua-mobile", "?0");
            connection.setRequestProperty("sec-ch-ua-platform", "\"macOS\"");
            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters = "username=" + URLEncoder.encode(username, StandardCharsets.UTF_8.name())
                    + "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8.name());

            log.info("====urlParameters====="+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("===response==="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    log.info("===response.toString()==="+new org.json.JSONObject(jsonResponse).optString("data", null));
                    // 假设响应体是一个JSON对象，包含token字段
                    // 使用适当的JSON库解析JSON字符串并获取token
                    // 这里使用org.json库作为示例
                    return new org.json.JSONObject(jsonResponse).optString("data", null);
                }
            } else {
               log.info("===处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

    /**
     * 创建用户
     *
     * @param user 用户信息
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String CreateUser(SysUser user, String contextPath,String MaxkbuserId,String username,String password) throws IOException {
        String loginEndpoint= contextPath+"/api/proxyapp/users/?a=1";
        log.info("==========loginEndpoint======="+loginEndpoint);
        //获取管理员token
        String token = loginAndGetToken(username, password,contextPath);
        log.info("==========token======="+token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters =String.format(
                    "{\"url\": \"/api/user_manage\","
                            + "\"method\": \"POST\","
                            + "\"body\": {"
                            + "\"email\": \"%s\","
                            + "\"username\": \"%s\","
                            + "\"password\": \"%s\","
                            + "\"nick_name\": \"%s\","
                            + "\"avatar\": \"%s\","
                            + "\"user_id\": \"%s\""
                            + "}}",
                    user.getEmail(), user.getUsername(), user.getPassword(),
                    user.getRealname(), user.getAvatar(), MaxkbuserId
            );
            log.info("=======新增用户body值====="+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("======响应======="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("======code======="+code);
                    if (code.equals("200")){
                        String dataObject = new org.json.JSONObject(jsonResponse).optString("data", null);
                        String innerDataObject = new org.json.JSONObject(dataObject).optString("data", null);
                        String id  = new org.json.JSONObject(innerDataObject).optString("id", null);
                        log.info("======id======"+id);
                        // 假设响应体是一个JSON对象，包含token字段
                        // 使用适当的JSON库解析JSON字符串并获取token
                        // 这里使用org.json库作为示例
                        return id;
                    }
                    return "";
                }
            } else {
                log.info("===处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String UpdateUser(SysUser user,String contextPath,String username,String password) throws IOException {
        String loginEndpoint= contextPath+"/api/proxyapp/users/?a=1";
         URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //获取管理员token
        String Token = loginAndGetToken(username, password,contextPath);

        try {
            // 设置请求方法
             connection.setRequestMethod("POST");
            // 设置请求头信息值
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",Token);
            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 创建请求体
            String jsonParameters =String.format(
                    "{\"url\": \"/api/user_manage\","
                            + "\"method\": \"PUT\","
                            + "\"body\": {"
                            + "\"user_id\": \"%s\","
                            + "\"email\": \"%s\","
                            + "\"avatar\": \"%s\","
                            + "\"nick_name\": \"%s\""
                            + "}}",
                    user.getMaxkbuserId(),user.getEmail(),user.getAvatar(), user.getRealname()
            );
            log.info("=======更新用户body值====="+jsonParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);

            }
            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("===响应==="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String dataObject = new org.json.JSONObject(jsonResponse).optString("data", null);
//                    String innerDataObject = new org.json.JSONObject(dataObject).optString("data", null);
//                    String id  = new org.json.JSONObject(innerDataObject).optString("id", null);
//                    log.info("===id==="+id);
                    // 假设响应体是一个JSON对象，包含token字段
                    // 使用适当的JSON库解析JSON字符串并获取token
                    // 这里使用org.json库作为示例
                    return dataObject;
                }
            } else {
                log.info("======处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("===Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

    /**
     * 删除用户
     *
     * @param maxkbuserId 用户id
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String DeleteUser(String maxkbuserId,String contextPath,String username,String password) throws IOException {
//        String loginEndpoint="http://"+contextPath+":8000/api/proxyapp/users/";
        String loginEndpoint= contextPath+"/api/proxyapp/users/";
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //获取管理员token值
        String Token = loginAndGetToken(username, password,contextPath);
        log.info("===========Token========"+Token);
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",Token);
            // 发送POST请求必须设置
            connection.setDoOutput(true);

            // 创建请求体
            String jsonParameters =String.format(
                    "{\"url\": \"/api/user_manage\","
                            + "\"method\": \"DELETE\","
                            + "\"body\": {"
                            + "\"user_id\": \"%s\""
                            + "}}",
                            maxkbuserId
            );
            log.info("=======删除用户body值====="+jsonParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
                log.info("=======input====="+input);
            }
            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("=====响应==="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    // 假设响应体是一个JSON对象，包含token字段
                    // 使用适当的JSON库解析JSON字符串并获取token
                    // 这里使用org.json库作为示例
                    return new org.json.JSONObject(jsonResponse).optString("data", null);
                }
            } else {
                log.info("===处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }



    /**
     * 创建知识库
     *
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String CreateKnowledgeBase(SysRole role, String contextPath, String MaxkbuserId,String username,String password) throws IOException {
        String loginEndpoint= contextPath+"/api/proxyapp/users/";
        log.info("============loginEndpoint======="+loginEndpoint);
        //获取管理员token
//        String username = "admin";
//        String password = "Infoclue@529";
        String token = loginAndGetToken(username, password,contextPath);
        log.info("============token======="+token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters =String.format(
                    "{\"url\": \"/api/dataset\","
                            + "\"method\": \"POST\","
                            + "\"body\": {"
                            + "\"name\": \"%s\","
                            + "\"desc\": \"%s\","
                            + "\"user_id\": \"%s\","
                            + "\"documents\": ["
                            + "  {"
                            + "    \"name\": \"%s\","
                            + "    \"paragraphs\": ["
                            + "      {"
                            + "        \"title\": \"\","
                            + "        \"content\": \"\""
                            + "      }"
                            + "    ]"
                            + "  }"
                            + "]"
                            + "}}",
                    role.getRoleName(),role.getDescription(),MaxkbuserId,role.getRoleName()
            );
            log.info("========新增知识库body值====="+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("=======响应======="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("=======code======="+code);
                    return "";
                }
            } else {
                log.info("===处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

    /**
     * 修改知识库名称
     *
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String editKnowledgeBase(String RoleName,SysRole role, String contextPath,String username,String password) throws IOException {
        String loginEndpoint= contextPath+"/api/proxyapp/dataset/";
        log.info("==========修改接口======="+loginEndpoint);
        //获取管理员token
        String token = loginAndGetToken(username, password,contextPath);
        log.info("========token========"+token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            // 设置请求方法
            connection.setRequestMethod("PUT");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters =String.format(
                    "{\"source_role_name\": \"%s\","
                            + "\"target_role_name\": \"%s\""
                            + "}",
                    RoleName,role.getRoleName()
            );
            log.info("========修改知识库名称body值====="+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应值
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("=======响应值========="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("=======返回结果========="+code);
                    return "";
                }
            } else {
                log.info("======处理错误响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }


/**
 * 删除知识库
 *
 * @throws IOException 如果网络请求过程中发生I/O错误
 */
public static String DeleteKnowledgeBase(SysRole role, String contextPath, String MaxkbuserId,String username,String password) throws IOException {
    String loginEndpoint= contextPath+"/api/proxyapp/users/";
    log.info("==========删除接口======="+loginEndpoint);
    //获取管理员token
    String token = loginAndGetToken(username, password,contextPath);
    log.info("============token=========="+token);
    // 创建URL对象
    URL url = new URL(loginEndpoint);
    // 打开连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {
        // 设置请求方法
        connection.setRequestMethod("POST");
        // 设置请求头信息
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("AUTHORIZATION",token);
        connection.setDoOutput(true);

        // 创建请求体
        String urlParameters =String.format(
                "{\"url\": \"/api/dataset\","
                        + "\"method\": \"DELETE\","
                        + "\"body\": {"
                        + "\"role_name\": \"%s\","
                        + "\"user_id\": \"%s\""
                        + "}}",
                role.getRoleName(),MaxkbuserId
        );
        log.info("========删除知识库body值====="+urlParameters);
        // 获取输出流并写入请求体
        try(OutputStream os = connection.getOutputStream()) {
            byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应值
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用BufferedReader读取响应
            try(BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("=======响应值======="+response);
                // 将响应转换为JSON字符串
                String jsonResponse = response.toString();
                String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                log.info("=======返回结果======="+code);
                return "";
            }
        } else {
            log.info("=====处理错误响应====="+responseCode);
            // 处理错误响应
            throw new IOException("Login failed with HTTP status: " + responseCode);
        }
    } finally {
        // 关闭连接
        connection.disconnect();
    }
}

/**
 * 赋予某个user某些role的权限
 *
 * @throws IOException 如果网络请求过程中发生I/O错误
 */
public static String assignment(SysUser user,SysRole role, String contextPath,String username,String password) throws IOException {
    String loginEndpoint= contextPath+"/api/proxyapp/users/";
    log.info("==========赋予接口======="+loginEndpoint);
    //获取管理员token
    String token = loginAndGetToken(username, password,contextPath);
    log.info("============token==========="+token);
    // 创建URL对象
    URL url = new URL(loginEndpoint);
    // 打开连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    try {
        // 设置请求方法
        connection.setRequestMethod("POST");
        // 设置请求头信息
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("AUTHORIZATION",token);
        connection.setDoOutput(true);

        // 创建请求体
        String urlParameters =String.format(
                "{\"url\": \"/api/team/member\","
                        + "\"method\": \"PUT\","
                        + "\"body\": {"
                        + "\"user_id\": \"%s\","
                        + "\"role_names\": [\"%s\"]"
                        + "}}",
                user.getMaxkbuserId(),role.getRoleName()
        );
        log.info("========赋予body值====="+urlParameters);
        // 获取输出流并写入请求体
        try(OutputStream os = connection.getOutputStream()) {
            byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应值
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 使用BufferedReader读取响应
            try(BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("=======赋予响应值======="+response);
                // 将响应转换为JSON字符串
                String jsonResponse = response.toString();
                String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                log.info("=======返回的结果======="+code);
                return "";
            }
        } else {
            log.info("=====处理赋予响应====="+responseCode);
            // 处理错误响应
            throw new IOException("Login failed with HTTP status: " + responseCode);
        }
    } finally {
        // 关闭连接
        connection.disconnect();
    }
 }

    /**
     * 删除用户某些知识库的权限
     *
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String deleteignment(SysRole role,String userid, String contextPath,String username,String password) throws IOException {
        String loginEndpoint = contextPath + "//api/proxyapp/dataset/";
        log.info("==========删除接口======="+loginEndpoint);
        //获取管理员token
        String token = loginAndGetToken(username, password,contextPath);
        log.info("=============token==========="+token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("DELETE");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters =String.format(
                    "{\"user_id\": \"%s\","
                            + "\"role_names\": [\"%s\"]"
                            + "}",
                    userid,role.getRoleName()
            );
            log.info("==========赋予body值====="+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 读取响应值
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 使用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("==========赋予响应值======="+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("==========返回的结果======="+code);
                    return "";
                }
            } else {
                log.info("========处理赋予响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

    /**
     * 上传文档到指定知识库
     *
     * @throws IOException 如果网络请求过程中发生I/O错误
     */
    public static String UploadDocument(KmDoc kmDoc, String contextPath, String MaxkbuserId, String username, String password) throws IOException {
        String loginEndpoint= contextPath+"/api/proxyapp/users/";
        //获取管理员token
        String token = loginAndGetToken(username, password,contextPath);
        log.info("==========token=========="+token);
        // 创建URL对象
        URL url = new URL(loginEndpoint);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        try {
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置请求头信息
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("AUTHORIZATION",token);
            connection.setDoOutput(true);

            // 创建请求体
            String urlParameters =String.format(
                    "{\"url\": \"/api/document\","
                            + "\"method\": \"POST\","
                            + "\"body\": {"
                            + "\"role_names\": [\"%s\"],"
                            + "\"user_id\": \"%s\","
                            + "\"documents\": ["
                            + "    {"
                            + "\"name\": \"%s\","
                            + "\"paragraphs\": ["
                            + "    {"
                            + "        \"title\": \"\","
                            + "        \"content\": \"\""
                            + "     }"
                            + "   ]"
                            + "  }"
                            + "]"
                            + "}}",
                    kmDoc.getCategory(),MaxkbuserId,kmDoc.getName()
            );
            log.info("=========指定body值========"+urlParameters);
            // 获取输出流并写入请求体
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = urlParameters.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 响应值
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 用BufferedReader读取响应
                try(BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    log.info("========赋予响应值========"+response);
                    // 将响应转换为JSON字符串
                    String jsonResponse = response.toString();
                    String code = new org.json.JSONObject(jsonResponse).optString("code", null);
                    log.info("========返回的结果========"+code);
                    return "";
                }
            } else {
                log.info("=====处理赋予响应====="+responseCode);
                // 处理错误响应
                throw new IOException("Login failed with HTTP status: " + responseCode);
            }
        } finally {
            // 关闭连接
            connection.disconnect();
        }
    }

 }
